Title: SQL W3S (By-BKK) / 034 Having
Tags: Obsidian_to_Anki

Q: What is the purpose of the SQL HAVING clause?
A: To filter groups based on an aggregate condition after grouping

Q: True or False: The WHERE clause can be used with aggregate functions like COUNT or SUM.
A: False

Q: Which clause allows filtering results of aggregated data in SQL?
A: HAVING clause

Q: Fill in the blank: HAVING clause is used with the _ clause to filter groups.
A: GROUP BY

Q: What is the main difference between HAVING and WHERE in SQL?
A: WHERE filters rows before grouping; HAVING filters groups after grouping

Q: Give an example of a situation where HAVING is needed instead of WHERE.
A: When you want only countries with more than 5 customers: HAVING COUNT(CustomerID) > 5

Q: Write a query to list countries with more than 5 customers using HAVING.
A: SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5

Q: Reverse card:
To filter groups based on aggregate conditions after grouping
A: What is the purpose of the SQL HAVING clause?

Q: Reverse card:
False
A: True or False: The WHERE clause can be used with aggregate functions like COUNT or SUM?

Q: True or False: HAVING can be used to filter groups created by GROUP BY.
A: True

Q: Which comes first in SQL: HAVING clause or GROUP BY clause?
A: GROUP BY comes first; HAVING comes after

Q: Write a query to show employees with more than 10 orders using HAVING.
A: SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID GROUP BY LastName HAVING COUNT(Orders.OrderID) > 10

Q: Fill in the blank: HAVING is used to filter results after _ functions have been applied.
A: Aggregate functions

Q: Give an example where HAVING and WHERE are used together.
A: SELECT Employees.LastName, COUNT(Orders.OrderID) AS NumberOfOrders FROM Orders INNER JOIN Employees ON Orders.EmployeeID = Employees.EmployeeID WHERE LastName = 'Davolio' OR LastName = 'Fuller' GROUP BY LastName HAVING COUNT(Orders.OrderID) > 25

Q: Reverse card:
HAVING is used with aggregate functions, WHERE is not
A: What is the main difference between HAVING and WHERE?

Q: True or False: HAVING clause must always follow GROUP BY in SQL queries.
A: True

Q: Example: Write a query to count customers by country, show countries with over 5 customers, sorted high to low.
A: SELECT COUNT(CustomerID), Country FROM Customers GROUP BY Country HAVING COUNT(CustomerID) > 5 ORDER BY COUNT(CustomerID) DESC